<?php

namespace App\Jobs;

use App\Models\HelpWorkOrder;
use App\Models\LogBalance;
use App\Models\Order;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

class RefundBalance implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $order, $discount;

    /**
     * RefundBalance constructor.
     * @param $order
     * @param float $discount
     */
    public function __construct($order, $discount = 1.0)
    {
        $this->order = $order;

        $this->discount = $discount;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //判断用户是否有申诉
        if (count($this->order->workOrders) > 0) {
            $this->order->refund_status = Order::REFUND_STATUS_UNDER_REVIEW;#复审中

            $this->order->save();

            return;
        }

        //判断订单状态已经退款
        if ($this->order->refund_at || !$this->order->paid_at) {
            return;
        }

        //判断是否双方同意退款
        if (
            $this->order->status == Order::STATUS_BOTH_CANCEL &&
            $this->order->user_distance < Order::DISTANCE_STANDARD &&
            $this->order->seller_distance < Order::DISTANCE_STANDARD
        ) {
            $this->discount = 1; #退全款
        } else {
            $this->discount = Order::REFUND_DISCOUNT; #退80%
        }

        $this->order->refund_status = Order::REFUND_STATUS_PROCESSING;#退款中

        $this->order->save();

        DB::transaction(function () {
            try {
                $total_amount = getMoneyFormat(($this->order->total_amount * $this->discount));

                $this->order->user->wallet->balance += getMoneyFormat($total_amount);

                $this->order->refund_status = Order::REFUND_STATUS_SUCCESS;

                $this->order->refund_at = Carbon::now();

                $this->order->schedule->status = $this->order->schedule->status == 2 ?: 0;

                $this->order->push();

            } catch ( \Exception $exception ) {
                $this->failed($exception);
            }
        });

    }

    public function failed(\Exception $e)
    {
        $this->order->refund_status = Order::REFUND_STATUS_UNDER_REVIEW;#复审中

        $this->order->remark = trans('admin.system') . trans('admin.refund_failed');

        $this->order->save();
    }
}
